package com.ranshiyan.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ranshiyan.entity.User;
import com.ranshiyan.service.UserService;
import com.ranshiyan.utils.CmsContant;

@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	UserService userService;
	
	//跳转到注册页面
	@RequestMapping(value="register",method=RequestMethod.GET)
	public String register(HttpServletRequest request) {
		request.setAttribute("user", new User());
		return "register";
	}
	
	@RequestMapping(value="register",method=RequestMethod.POST)
	public String register(HttpServletRequest request,@Valid @ModelAttribute("user")User user,BindingResult result) {
		if(result.hasErrors()) {
			return "register";
		}
		if(user.getUsername().contains("3")) {
			result.rejectValue("username"," ","用户名称不能包含数字3");
		}
		if(result.hasErrors()) {
			return "register";
		}
		int reigsterResult = userService.register(user);
		
		if(reigsterResult>0) {
			return "redirect:login";
		}
		request.setAttribute("error", "注册失败");
		return "register";
	}
	
	
	//转到登录页面
	@RequestMapping(value="login",method=RequestMethod.GET)
	public String login(HttpServletRequest request) {
		request.setAttribute("user", new User());
		return "login";
	}
	
	//接收登录页面的数据 进行登录操作
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(HttpServletRequest request,User user) {
		
		User loginUser = userService.login(user);
		System.out.println(loginUser);
		if(loginUser!=null) {
			System.out.println(111);
			request.getSession().setAttribute(CmsContant.USER_KEY, loginUser);
			return loginUser.getRole()==CmsContant.POLE_ADMIN?"redirect:/admin/index":"redirect:/user/home";
		}
		return "login";
	}
	
	@RequestMapping("checkuser")
	@ResponseBody
	public boolean checkuser(String username) {
		User user = userService.findByName(username);
		return (user==null);
	}
	
	@RequestMapping("home")
	public String home(HttpServletRequest request) {
		return "home/index";
	}
	
}
